package com.sopaths.crawler.tasks;

import java.util.concurrent.atomic.AtomicBoolean;

import com.sopaths.contract.crawler.CrawlerTaskSource;
import com.sopaths.contract.crawler.CrawlerTaskType;

public class AbstractCrawlerTask<T> implements CrawlerTask<T> {

	private T result;

	private AtomicBoolean finished = new AtomicBoolean(false);

	private String url;

	private CrawlerTaskSource source;

	private CrawlerTaskType type;

	public T getResult() {
		synchronized (finished) {
			while (!finished.get()) {
				try {
					finished.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			return result;
		}
	}

	public void setResult(T result) {
		this.result = result;
	}

	public boolean isFinished() {
		return finished.get();
	}

	public void finish() {
		synchronized (finished) {
			finished.compareAndSet(false, true);
			finished.notifyAll();
		}
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public CrawlerTaskSource getSource() {
		return source;
	}

	public void setSource(CrawlerTaskSource source) {
		this.source = source;
	}

	public CrawlerTaskType getType() {
		return type;
	}

	public void setType(CrawlerTaskType type) {
		this.type = type;
	}

	public String toString() {
		StringBuilder representationBuilder = new StringBuilder();
		representationBuilder.append(System.lineSeparator()).append("Source: ").append(source);
		representationBuilder.append(System.lineSeparator()).append("Type: ").append(type);
		representationBuilder.append(System.lineSeparator()).append("URL: ").append(url);
		return representationBuilder.toString();
	}
}
